
import Common from './common';

import FormEditAction from '../components/AddPage/actions/formEdit';

import {getQueryCondition} from '../../../../hrpub/common/utils/utils';
import setInitValue from "../../../public/functions/setInitValue";

export default class BatchAddAction extends Common {

    constructor(comp) {
        super();
        this.comp = comp;
    }

    extend = [FormEditAction]

    didMount = () => {
    }

    // 给批量新增弹窗的查询弹窗添加查询信息
    addQueryConditionToMultiAddSearch = (template) => {
        const {props} = this.comp;
        const {emp} = props;

        template['search_batch'].items.map((item) => {
            if(item.attrcode === 'hi_psnjob.clerkcode') {
                item.queryCondition = {
                    pk_org: emp.orgValue.refpk,
                    GridRefActionExt: 'nccloud.web.hryf.pub.sqlbuilder.BatchAddClerkcodeRefSqlBuilder',
                    optype: 5
                };
            }
        });
    }

    // 打开批量新增的查询台窗
    openBatchAddSearchModal = () => {
        const {props} = this.comp;
        const {search, meta} = props;
        let template = meta.getMeta();

        this.addQueryConditionToMultiAddSearch(template);

        search.openAdvSearch('search_batch', true);
    }

    historyState = null;

    // 初始化弹窗
    initBatchModal = async () => {
        const {
            props: {
                dispatch,
                emp
            }
        } = this.comp;

        let postData = {
            pk_org: emp.orgValue.refpk
        };
        
        let res = await dispatch({
            type: 'emp/initBatchAddModal',
            payload: {
                postData: postData
            }
        });

        if(res.success) {
            return res;
        }
    }

    // 打开批量新增弹窗
    openBatchModal = async () => {
        const {
            props: {
                dispatch,
                emp
            }
        } = this.comp;

        let initRes = await this.initBatchModal();
 
        if(initRes) {
            dispatch({
                type: 'emp/update',
                payload: {
                    batchAddModalVisible: true,
                    batchAddSelectManRefer: initRes.data.psnItemMeta
                }
            });
        }
    }

    // 关闭批量新增弹窗
    closeBatchModal = () => {
        this.comp.props.dispatch({
            type: 'emp/update',
            payload: {
                batchAddModalVisible: false,
                batchAddCurrentStep: 0
            }
        });
    }

    // 为了解决查询不能是async的问题
    toSearchWrapper = () => {
        this.toSearch();
    }

    // 批量新增弹窗第一步条件选择查询弹窗点击确认
    toSearch = async () => {
        const {props} = this.comp;
        const {dispatch, emp, editTable, search, meta} = props;

        let template = meta.getMeta();
        let postData = {
            ...getQueryCondition(props, 'search_batch'),
            listpks: this.getExistPks(),
            oid: template['search_batch'].oid,
            pk_org: emp.orgValue.refpk
        };

        try {
            let res = await dispatch({
                type: 'emp/getBatchAddTableDataBySearch',
                payload: {
                    postData: postData
                }
            });
            if(res.success && res.data && res.data.list_batch) {
                editTable.setTableData('list_batch', res.data.list_batch.list_batch);
            }
        }
        catch(e) {
            console.error(`toSearch: ${e}`);
        }
    }

    // 获取已存在的listpks
    getExistPks = () => {
        const {props} = this.comp;
        const {dispatch, emp, editTable} = props;

        let tableData = editTable.getAllRows('list_batch');

        let listpks = tableData.map((item) => {
            return item.values['pk_psnjob'].value;
        });

        return listpks.join(',')
    }

    // 批量新增弹窗第一步参照选择逻辑
    changePersonRefer = async (value) => {
        const {props} = this.comp;
        const {dispatch, emp, editTable} = props;

        let postData = {
            listpks: this.getExistPks(),
            pk_org: emp.orgValue.refpk,
            refpks: ''
        };

        let refpks = value.map((item) => {
            return item.refpk;
        });
        postData['refpks'] = refpks.join(',');

        try {
            let res = await dispatch({
                type: 'emp/getBatchAddTableDataByRefer',
                payload: {
                    postData: postData
                }
            });

            if(res.data && res.data.confirmMsg) {
                this.toast({
                    color: 'danger',
                    content: res.data.confirmMsg
                });
            }

            if(res.success && res.data && res.data.list_batch) {
                editTable.setTableData('list_batch', res.data.list_batch.list_batch);
            }
        }
        catch(e) {
            console.error(`changePersonRefer: ${e}`);
        }
    }

    // 获取并存储选择的行
    getSelectedRows = () => {
        const {props, state} = this.comp;
        const {emp, dispatch, editTable} = props;

        let selectedRows = [];

        // if(state.selectAll) {
        //     selectedRows = editTable.getAllRows('list_batch');
        // }
        // else {
            selectedRows = editTable.getCheckedRows('list_batch').map((item) => {
                return item.data
            });
        // }

        this.comp.setState({
            selectRows: this.deepCopy(selectedRows)
        });

        return selectedRows;
    }

    // 批量添加弹窗点击下一步
    goToNextStep = async () => {
        const {props, action} = this.comp;
        const {emp, dispatch, editTable, form, meta} = props;

        let template = meta.getMeta();

        this.historyState = this.deepCopy(editTable.getAllRows('list_batch'));

        let postData = {
            pk_org: emp.orgValue.refpk
        };
        
        let selectRows = this.getSelectedRows();

        if(selectRows && selectRows.length <= 0) {
            this.toast({
                color: 'warning',
                content: emp.language['gx6008-000283'] //'请选择要办理兼职的人员!'
            });
        }
        else {
            try {
                let res = await dispatch({
                    type: 'emp/batchAddNextStep',
                    payload: {
                        postData: postData
                    }
                });

                template['formrelation']['card_batch'] = [];
                template['formrelation']['card'].map((item) => {
                    let name = `batch${item}`;
                    template[name] = {
                        ...this.deepCopy(res.data.template[item]),
                        code: name,
                        relationcode: name
                    }
                    template['formrelation']['card_batch'].push(name);
                });
                template['list'] = res.data.template['list'];
                template['card_batch'] = this.deepCopy(res.data.template['card']);

                let newTemplate = action.pAct.processTemplate(template);

                meta.setMeta(newTemplate, () => {
                    dispatch({
                        type: 'emp/update',
                        payload: {
                            batchAddCurrentStep: 1
                        }
                    });
                    form.setFormStatus('card_batch', 'edit');

                    setTimeout(() => {
                        setInitValue(props, 'card',  res.data.formData.head.card)

                        form.setAllFormValue({
                            card_batch: res.data.formData.head.card
                        });
                    }, 10);
                    
                    /*setTimeout(() => {
                        template['formrelation']['card_batch'].map((item) => {
                            form.openArea(item);
                        });
                    },2);*/
                });
            }
            catch(e) {
                console.error(e);
            }
        }
    }

    // 批量添加弹窗点击上一步
    goToPrevStep = () => {
        const {props} = this.comp;
        const {emp, dispatch, editTable} = props;

        dispatch({
            type: 'emp/update',
            payload: {
                batchAddCurrentStep: 0
            }
        });

        if(this.historyState) {
            editTable.setTableData('list_batch', {rows: this.historyState}, false);
            this.historyState = null;
        }
    }

    // 当表格选择全部的时候
    selectedAll = (...args) => {
        this.comp.setState({
            selectAll: args[2]
        });
    }

    // 第二步表单编辑前
    // formBeforeEdit = async (fprops, moduleId, key, value, data) => {
    //     const {props, state} = this.comp;
    //     const {emp, dispatch, meta} = props;

    //     let postData = {
    //         key: key,
    //         pk_org: emp.orgValue.refpk
    //     };

    //     try {
    //         let res = await dispatch({
    //             type: 'emp/batchAddModalFormEditBefore',
    //             payload: {
    //                 postData: postData
    //             }
    //         });
    //         if(res.success) {
    //             let template = meta.getMeta();
    //             if(res.data && res.data.refParam) {
    //                 template['card_batch'].items.map((item) => {
    //                     if(item.attrcode === key) {
    //                         Object.assign(item.queryCondition, res.data.refParam);
    //                     }
    //                 });
    //             }
    //             await new Promise((resolve, reject) => {
    //                 meta.setMeta(template, resolve);
    //             });
    //         }
    //     }
    //     catch(e) {
    //         console.error(`formBeforeEdit: ${e}`);
    //     }
    //     return true;
    // }

    // 批量新增弹窗第二步编辑后
    // formAfterEdit = async (fprops, moduleId, key, value, data) => {
    //     const {props, state} = this.comp;
    //     const {emp, dispatch, meta, form} = props;

    //     let postData = {
    //         key: key,
    //         model: form.getAllFormValue('card_batch'),
    //         pk_org: emp.orgValue.refpk
    //     };

    //     try {
    //         let res = await dispatch({
    //             type: 'emp/batchAddModalFormEditAfter',
    //             payload: {
    //                 postData: postData
    //             }
    //         });

    //         if(res.success) {
    //             form.setAllFormValue({
    //                 card_batch: res.data.card
    //             });
    //         }
    //     }
    //     catch(e) {
    //         console.error(`formAfterEdit: ${e}`);
    //     }
    // }

    // 批量新增弹窗点击完成
    submitBatchAdd = async () => {
        const {props, state} = this.comp;
        const {emp, dispatch, meta, form} = props;

        if(!form.isCheckNow('card_batch')) {
            return;
        }

        let postData = {
            listpks: '',
            formData: form.getAllFormValue('card_batch'),
            pk_org: emp.orgValue.refpk
        };

        let listpks = state.selectRows.map((item) => {
            return item.values['pk_psnjob'].value
        });

        postData['listpks'] = listpks.join(',');

        try {
            let res = await dispatch({
                type: 'emp/batchAddModalSubmit',
                payload: {
                    postData: postData
                }
            });

            if(res.success) {
                this.toast({
                    color: 'success',
                    content: emp.language['gx6008-000066'] // 新增成功
                });
                this.closeBatchModal();
                this.pubSub.publish('getMainTableData');
            }
        }
        catch(e) {
        }
    }
}